<template>
  <div v-if="visible" class="dialog-overlay">
    <div class="container" :class="{ 'maximized': isMaximized }">
      <div class="window-controls">
        <button class="window-control" @click="toggleMaximize" title="全屏/还原">
          <svg v-if="isMaximized" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M8 3V5H5V8H3V3H8Z" fill="currentColor"/>
            <path d="M21 8V3H16V5H19V8H21Z" fill="currentColor"/>
            <path d="M3 16V21H8V19H5V16H3Z" fill="currentColor"/>
            <path d="M19 16V19H16V21H21V16H19Z" fill="currentColor"/>
          </svg>
          <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M3 8V3H8V5H5V8H3Z" fill="currentColor"/>
            <path d="M21 3H16V5H19V8H21V3Z" fill="currentColor"/>
            <path d="M8 21H3V16H5V19H8V21Z" fill="currentColor"/>
            <path d="M19 19V16H21V21H16V19H19Z" fill="currentColor"/>
          </svg>
        </button>
        <button class="window-control close-btn" @click="closeDialog" title="关闭">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M18 6L6 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
            <path d="M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      <h1 class="title">{{title || 'AI响应'}}</h1>

      <!-- 对话历史 -->
      <div class="chat-history">
        <div v-for="(message, index) in messages" :key="index" class="message-item">
          <div class="message-content"  v-if="message.role != 'user'" :class="[message.role, { 'is-streaming': message.isStreaming }]">
            <div v-if="message.role === 'user'" class="user-avatar">用户</div>
            <div v-else class="bot-avatar">AI</div>
            <div v-html="renderMarkdown(message.content)" class="markdown-content"></div>
          </div>
        </div>
      </div>

      <!-- 控制按钮 -->
      <div class="control-area">
        <button 
          v-if="isStreaming"
          @click="stopGeneration"
          class="action-btn streaming"
        >
          <div class="streaming-dots">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
          </div>
          停止生成
        </button>
        <button 
          @click="clearMessages"
          class="action-btn clear-btn"
        >
          清屏
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import { addGbAiAskResp } from '@/api/buss/gbaiaskresp.js'
 
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  initialMessages: {
    type: Array,
    default: () => []
  },
  apiKey: {
    type: String,
    default: import.meta.env.VITE_APP_DEEPSEEK_APIKEY  // 默认API Key
  }
})

const messages = ref([...props.initialMessages])
const isStreaming = ref(false)
const abortController = ref(new AbortController()) 
const visible = ref(false)
const isMaximized = ref(false)

// 初始化marked配置
marked.setOptions({
  breaks: true,
  gfm: true,
  highlight: (code) => hljs.highlightAuto(code).value
})

// 停止生成
const stopGeneration = () => {
  try {
    if (abortController.value && !abortController.value.signal.aborted) {
      abortController.value.abort()
      console.log('已中止当前生成请求')
    }
    abortController.value = new AbortController()
    isStreaming.value = false
    
    // 确保移除所有流式传输中的消息
    messages.value = messages.value.map(msg => {
      if (msg.isStreaming) {
        return {...msg, isStreaming: false}
      }
      return msg
    }).filter(msg => msg.content.trim().length > 0)
  } catch (error) {
    console.error('停止生成时出错:', error)
  }
}

// 渲染Markdown内容
const renderMarkdown = (text) => {
  return marked.parse(text || '')
}

function openDialog() {
  visible.value = true
}

function closeDialog() {
  visible.value = false
  stopGeneration()
}

function toggleMaximize() {
  isMaximized.value = !isMaximized.value
}

// 清空消息
const clearMessages = () => {
  messages.value = []
}

// 暴露方法给父组件
defineExpose({ 
  openDialog, 
  closeDialog,
  stopGeneration,
  clearMessages,
  addMessage: (message) => {
    messages.value.push(message)
  },
  startStreaming: () => {
    isStreaming.value = true
  },
  stopStreaming: () => {
    isStreaming.value = false
  },
  queryAI: async (prompt) => {
    isStreaming.value = true
    abortController.value = new AbortController()
    
    try {
      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${props.apiKey}`
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: [...messages.value, {role: 'user', content: prompt}],
          stream: true,
          temperature: 0.7,
          max_tokens: 2000
        }),
        signal: abortController.value.signal
      })

      if (!response.ok) throw new Error('API请求失败')

      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let partialResult = ''
      
      while (true) {
        const { done, value } = await reader.read()
        if (done) {
         
          break
        }

        const chunks = decoder.decode(value).split('\n\n')
        for (const chunk of chunks) {
          if (chunk.startsWith('data: ')) {
            try {
              const data = JSON.parse(chunk.replace('data: ', ''))
              if (data.choices?.[0]?.delta?.content) {
                partialResult += data.choices[0].delta.content
                
                // 更新最新消息内容
                const lastIndex = messages.value.length - 1
                if (lastIndex >= 0) {
                  messages.value[lastIndex].content = partialResult
                }
              }
              
              if (data.event === 'end'||data.event === 'DONE'  || data.finish_reason) {
                isStreaming.value = false
               
                break
              }
            } catch (e) {
              // 忽略解析错误
            }
          }
        }
      }
    } catch (error) {
      console.error('流式传输错误:', error)
      addMessage({
        role: 'assistant',
        content: '生成过程中发生错误: ' + error.message
      })
    } finally {
      isStreaming.value = false
       // 记录日志
                const lastMessage = messages.value[messages.value.length - 1]
                if (lastMessage?.role === 'assistant') {
                  console.log('准备记录日志:', {
                    ask: prompt,
                    response: lastMessage.content,
                    MenuName: 'deepseek-chat'
                  })
                  addGbAiAskResp({
                    ask: prompt,
                    response: lastMessage.content,
                    ChatModel: 'deepseek-chat',
                    createTime: new Date().toISOString()
                  })
                  .then(() => console.log('日志记录成功'))
                  .catch(e => {
                    console.error('日志记录失败:', e)
                    if (e.response) {
                      console.error('响应数据:', e.response.data)
                      console.error('状态码:', e.response.status)
                    }
                  })
                }
    }
  }
})
</script>

<style scoped>
/* 保留原有样式，移除输入框相关样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  backdrop-filter: blur(5px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  transition: all 0.3s ease;
}

.container {
  background: white;
  width: 90%;
  max-width: 800px;
  height: 80vh;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 25px rgba(0,0,0,0.2);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.container.maximized {
  width: 100%;
  height: 100vh;
  max-width: none;
  border-radius: 0;
}

.window-controls {
  position: absolute;
  top: 0;
  right: 0;
  z-index: 10;
  display: flex;
  gap: 4px;
  padding: 8px;
}

.window-control {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: none;
  border: none;
  border-radius: 4px;
  color: #666;
  transition: all 0.3s;
}

.window-control:hover {
  background: rgba(0,0,0,0.05);
  color: #333;
}

.window-control svg {
  transition: transform 0.2s;
}

.window-control:hover svg {
  transform: scale(1.1);
}

.close-btn:hover {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.title {
  text-align: center;
  color: var(--text-color);
  margin: 1.5rem 0;
  font-size: 1.8rem;
  position: relative;
  padding: 0 2rem;
  font-weight: 600;
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 1rem;
  background: #f8f9fa;
  margin: 1rem;
}

.message-item {
  margin-bottom: 1.5rem;
}

.message-content {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}

.user-avatar,
.bot-avatar {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  min-width: 60px;
  text-align: center;
}

.user-avatar {
  background: #3498db;
  color: white;
}

.bot-avatar {
  background: #2ecc71;
  color: white;
}

.markdown-content {
  flex: 1;
  background: white;
  padding: 1rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  line-height: 1.6;
}

.markdown-content :deep(pre) {
  background: #2d2d2d;
  padding: 1rem;
  border-radius: 4px;
  overflow-x: auto;
}

.markdown-content :deep(code) {
  font-family: 'Fira Code', monospace;
  padding: 2px 4px;
  background: #f0f0f0;
  border-radius: 3px;
}

.control-area {
  display: flex;
  justify-content: center;
  padding: 1rem;
}

.action-btn {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 0.5rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.action-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.clear-btn {
  background: #3498db;
  margin-left: 10px;
}

.streaming-dots {
  display: flex;
  gap: 4px;
  animation: bounce 1.4s infinite;
}

.streaming-dots .dot {
  width: 6px;
  height: 6px;
  background: white;
  border-radius: 50%;
}

.message-content.assistant.is-streaming {
  position: relative;
  min-height: 40px;
  padding-right: 3rem;
}

.message-content.assistant.is-streaming::after {
  content: "•••";
  position: absolute;
  right: 1rem;
  bottom: 0.5rem;
  animation: blink 1s infinite;
}

.message-content.assistant:not(.is-streaming)::after {
  display: none !important;
  visibility: hidden !important;
  height: 0;
  width: 0;
  overflow: hidden;
}

@keyframes blink {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes bounce {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-3px); }
}
</style>